// utils/socket.js
export default class Socket {
  constructor(url) {
    this.ws = null;
    this.url = url;
    this.callbacks = []; // 存储页面回调函数
  }

  connect() {
    this.ws = uni.connectSocket({
      url: this.url,
      header: { 'content-type': 'application/json' }
    });
    this.ws.onMessage(res => {
      const data = JSON.parse(res.data);
      this.callbacks.forEach(cb => cb(data)); // 触发所有页面回调
    });
    this.ws.onClose(() => {
      console.log("连接关闭，尝试重连...");
      setTimeout(() => this.connect(), 2000);
    });
  }

  // 注册页面回调
  addCallback(callback) {
    this.callbacks.push(callback);
  }

  // 移除页面回调
  removeCallback(callback) {
    this.callbacks = this.callbacks.filter(cb => cb !== callback);
  }

  send(data) {
    this.ws.send({ data: JSON.stringify(data) });
  }

  close() {
    this.ws.close();
  }
}